package trading.spring;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;


import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;

/**
 * A sub-class of {@link VelocityLayoutView} which includes in the template
 * context default values provided by {@link DefaultValuesPopulator}. Gets
 * used in place of the usual {@link VelocityLayoutView} thanks to the
 * {@link DefaultValuesVelocityLayoutViewResolver}. 
 * @author dcrosta
 */
public class DefaultValuesVelocityLayoutView extends VelocityLayoutView {
    
    /**
     * This method gets the default values from the {@link DefaultValuesPopulator}
     * and makes them available in the Velocity template context. Called by Spring
     * when a View is being rendered.
     * @param context the {@link VelocityContext} about to be rendered
     * @param response the {@link HttpServletResponse} the template will be rendered to
     * @throws Exception if thrown by Velocity
     */
    @Override
    protected void doRender(Context context, HttpServletResponse response) throws Exception {
    	Map<String, Object> templateValues = getDefaultValues(context);
        for ( Entry<String, Object> entry : templateValues.entrySet() ) {
            context.put(entry.getKey(), entry.getValue());
        }
        
        super.doRender(context, response);
    }
    
    /**
     * Get the Map of default values from the {@link DefaultValuesPopulator}. No
     * sense in caching the populator as an instance member, since Spring creates
     * a new instance of this class for each view that is rendered.
     * @return the map of default template values
     */
    private Map<String, Object> getDefaultValues(Context context) {
        // This class isn't (can't be) a Spring @Component, so
        // we have to do our bean lookup manually. ~dcrosta
        
 	 	return new HashMap<String, Object>();
    }
}
